# -*- coding:utf-8 -*-
## author : cypro666
## note   : python3.4+
"""
simple wrapper of redis operations, based on python redis library  
"""
import redis as pyredis
from threading import RLock
from .utilities import DummyLock


# default redis host and port
DEFAULT_REDIS_HOST = 'localhost'
DEFAULT_REDIS_PORT = 6379


class RedisCMD(object):
    """ RedisCMD is both redis client and command wildcard template wrapper """ 
    __slots__ = ('__client','__cmd','__lock')
    
    def __init__(self, s, host=None, port=None, lock=False):
        """ if `lock` is true, using RLock else DummyLock """
        self.__cmd = s
        if host and port:
            self.__client = pyredis.Redis(host=host,port=port)
            try:
                self.__client.ping()
            except:
                raise RuntimeError('Could Not Connect to %s:%d\n' % (host, port))
        self.__lock = RLock() if lock else DummyLock()
    
    def __str__(self):
        """ return current command str template """
        return self.__cmd
    
    def __repr__(self):
        """ return current command str template """
        return self.__cmd
    
    def execute(self, *args):
        """ fill command template with `args` and execute command """
        with self.__lock:
            return self.__client.execute_command(*(self.__cmd % args).split())
    
    def __call__(self, *args):
        """ callable support, see test for more details """
        with self.__lock:
            return self.__client.execute_command(*(self.__cmd % args).split()) 
        
    def assign(self, s):
        """ assign new command wildcard template """
        self.__cmd = s
        return self



def test():
    rcmd = RedisCMD('SET %s %s', DEFAULT_REDIS_HOST, DEFAULT_REDIS_PORT, True)
    print(rcmd)
    print(rcmd.execute('foo', 'bar'))
    print(rcmd.assign('DBSIZE').execute())
    rcmd.assign('GET %s')
    print(rcmd.execute('foo'))
    print(rcmd.assign('DEL foo').execute())
    print(rcmd.assign('DBSIZE')())




